package com.bayss.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.DateUtil;
import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.constant.ResultMsg;
import com.bayss.core.entity.user.AddressInfo;
import com.bayss.core.entity.user.UserInfo;
import com.bayss.core.model.WxConfig;
import com.bayss.core.service.address.AddressFixedInfoService;
import com.bayss.core.service.address.AddressService;
import com.bayss.core.service.user.UserService;
import com.bayss.core.util.DataTypeUtils;
import com.bayss.web.uresponse.UserResponse;
import com.bayss.web.utlis.ParseUrl;
import com.bayss.web.verify.ParamVerify;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户操作
 *
 * @author yangjian
 */
@Slf4j
@RestController
public class UserController extends ApiBaseController{

    private final UserService userService;

    private final AddressService addressService;
    private final AddressFixedInfoService addressFixedInfoService;

    @Autowired
    public UserController(UserService userService, AddressService addressService,AddressFixedInfoService addressFixedInfoService) {
        this.userService = userService;
        this.addressService = addressService;
        this.addressFixedInfoService = addressFixedInfoService;
    }

    @RequestMapping(value = "/user/login.json")
    public ResultMsg login(@ParamVerify(isNotBlank = true)String code,
                           @ParamVerify(isNotNull = true)String avatar_url,
                           @ParamVerify(isNotNull = true)String nick_name,
                           @ParamVerify(isNotNull = true)String gender) {
        String url1 = "https://api.weixin.qq.com/sns/jscode2session?appid="+ WxConfig.appid +"&secret="+ WxConfig.WX_SECRET +"&js_code=";
        String url2 = "&grant_type=authorization_code";
        UserInfo user;
        try {
            String userInfo = ParseUrl.getDataFromUrl((url1+code+url2));
            if (StringUtils.isBlank(userInfo)) {
                throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "js code 2 session is fail");
            }
            JSONObject userObj = JSONObject.parseObject(userInfo);
            if (userObj.containsKey("errcode")) {
                throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, userObj.getString("errmsg"));
            }
            user = userService.login(userObj.getString("openid"), nick_name, avatar_url, gender);
        } catch (Exception e) {
            log.error("login is error", e);
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "login is fail");
        }
        return ResultMsg.success(user);
    }

    /**
     * 更新用户
     */
    @RequestMapping("/user/update.json")
    public ResultMsg updateUser(Long id, String cellphone, String domain, Integer gender,String hobby,String birthday) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setCellphone(cellphone);
        userInfo.setDomain(domain);
        userInfo.setGender(gender);
        userInfo.setHobby(hobby);
        userInfo.setBirthday(DataTypeUtils.toDate(birthday));
        userService.updateUserInfo(userInfo);
        return ResultMsg.success();
    }

    /**
     * 用户信息
     */
    @RequestMapping("/user/info.json")
    public ResultMsg info(@RequestParam(name = "uid", required = true)Long uid) {
        return ResultMsg.success(userService.getUser(uid));
    }

    /**
     * 设置电话
     */
    @RequestMapping("/user/callPhone_set.json")
    public ResultMsg info(UserResponse userResponse,
                          @RequestParam(name = "tel") String tel,
                          @RequestParam(name = "code") String code) {
        return ResultMsg.success(userService.updateTel(tel, userResponse.getUid(), code));
    }

    /**
     * 添加地址
     * @return
     */
    @RequestMapping("/address/save.json")
    public ResultMsg addAddress(UserResponse userResponse,
                                @RequestParam(name = "id", required = false) Long id,
                                @RequestParam(name = "recvName", required = false) String recvName,
                                @RequestParam(name = "recvPhone", required = false) String recvPhone,
                                @RequestParam(name = "recvAddr", required = false) String recvAddr,
                                @RequestParam(name = "gender", required = false) Integer gender,
                                @RequestParam(name = "houseNumber", required = false, defaultValue = "") String houseNumber,
                                @RequestParam(name = "tab", required = false) Integer tab,
                                @RequestParam(name = "fixAddrId", required = false) Long fixAddrId,
                                @RequestParam(name = "defaultAddr", required = false, defaultValue = "0") Integer defaultAddr,
                                @RequestParam(name = "longitude", required = false) String longitude,
                                @RequestParam(name = "latitude", required = false) String latitude) {
        AddressInfo addressInfo = AddressInfo.builder()
                .uid(userResponse.getUid())
                .id(id)
                .receivingName(recvName)
                .receivingCellphone(recvPhone)
                .receivingAddr(recvAddr)
                .gender(gender)
                .houseNumber(houseNumber)
                .tab(tab)
                .fixAddrId(fixAddrId)
                .defaultAddr(defaultAddr)
                .longitude(longitude)
                .latitude(latitude)
                .build();
        boolean res = addressService.save(addressInfo);
        if (!res) {
            log.warn("add addr is fail");
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "add addr is fail");
        }
        return ResultMsg.success();
    }

    /**
     * 修改地址
     */
    @RequestMapping("/address/update.json")
    public ResultMsg updateAddress() {
        return ResultMsg.success();
    }


    /**
     * 地址信息
     */
    @RequestMapping("/address/list.json")
    public ResultMsg addressList(UserResponse userResponse) {
        return ResultMsg.success(addressService.getByUserId(userResponse.getUid()));
    }

    /**
     * 设置默认地址（并取消其它地址默认）
     * @param userResponse
     * @param id
     * @return
     */
    @RequestMapping("/address/setDefault.json")
    public ResultMsg setDefault(UserResponse userResponse,Long id) {
        addressService.setDefaultAddr(userResponse.getUserInfo(), id);
        return ResultMsg.success();
    }
    /**
     * 地址信息
     */
    @RequestMapping("/address/del.json")
    public ResultMsg addressDel(UserResponse userResponse,
                                @RequestParam(name = "addrId") Long addrId) {
        return ResultMsg.success(addressService.delAddr(addrId));
    }

    /**
     * 固定地址查询
     */
    @RequestMapping("/address/fixedAddressList.json")
    public ResultMsg fixedAddressList(UserResponse userResponse) {
        return ResultMsg.success(addressFixedInfoService.getAddressFixedList());
    }
}
